package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisRedisService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisRedisService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {

    @Reference
        private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    @Reference
    private IStrategyDetailService detailService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private IStrategyStatisRedisService strategyStatisRedisService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private ITravelStatisRedisService travelStatisRedisService;

    @Value("${file.path}")
    private String basePath;

    @RequestMapping("")
    public String index(Model model, @ModelAttribute("qo") TravelQuery qo, @UserParam UserInfo userInfo){
        PageInfo pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("userInfo",userInfo);
        //tcs 最新的游记动态
        List<TravelComment> list = travelCommentService.listNewsCommends();
        model.addAttribute("tcs",list);

        //hs 热门的攻略
        List<StrategyDetail> hs = strategyDetailService.getHotsTop5();
        model.addAttribute("hs",hs);
        return "/travel/list";
    }

    //进入编辑页面
    @RequestMapping("/input")
    public String input(Model model,Long id){
        List<Destination> list = destinationService.list();
        model.addAttribute("dests",list);
        if(id != null){
            //回显游记信息
            Travel travel = travelService.get(id);
            model.addAttribute("tv",travel);
            TravelContent content = travelService.getContent(id);
            travel.setTravelContent(content);
        }
        return "/travel/input";
    }


    //进入某一篇游记
    @RequestMapping("/detail")
    public String detail(Long id, Model model,@UserParam UserInfo userInfo){
        //detail(游记)
        Travel travel = travelService.get(id);
        TravelContent content = travelService.getContent(id);
        travel.setTravelContent(content);
        model.addAttribute("detail",travel);
        //toasts
        List<Destination> toasts = destinationService.getToasts(travel.getDest().getId());
        //dest
        Destination dest = toasts.remove(toasts.size() - 1);
        model.addAttribute("toasts",toasts);
        model.addAttribute("dest",dest);

        //sds 相关攻略
        List<StrategyDetail> sds = detailService.queryViewNumTop3(dest.getId());
        model.addAttribute("sds",sds);

        //ts 相关游记
        List<Travel> ts = travelService.getViewNumTop3(dest.getId());
        model.addAttribute("ts",ts);

        //共享当前登录用户
        model.addAttribute("userInfo",userInfo);

        //查询游记的评论内容
        TravelCommentQuery query = new TravelCommentQuery();
        query.setTravelId(id);
        query.setPageSize(Integer.MAX_VALUE); //不分页
        Page page = travelCommentService.query(query);
        model.addAttribute("list",page.getContent());
        return "/travel/detail";
    }

    //游记的新增或修改
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo user){
        //获取当前用户
        /*String token = CookieUtil.getToken(req, resp);
        String userStr = userInfoRedisService.getToken(token);
        UserInfo userInfo = JSON.parseObject(userStr, UserInfo.class);*/
        if(user == null){
            return new AjaxResult(false,"大哥,先去登录");
        }
        travel.setAuthor(user);
        Long id = travelService.saveOrUpdate(travel);
        return AjaxResult.SUCCESS.addData(id);
    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, basePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    //游记评论
    @RequestMapping("/commentAdd")
    public String commentAdd(Model model, TravelComment comment,int floor,@UserParam UserInfo userInfo){

        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());
        comment.setCity(userInfo.getCity());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setLevel(userInfo.getLevel());
        TravelComment travelComment = travelCommentService.saveOrUpdate(comment);

        //c
        model.addAttribute("c",travelComment);
        //floor
        model.addAttribute("floor",travelCommentService.getFloor(comment.getTravelId()));
        return "/travel/commentTpl";
    }


    //游记收藏:/travel/favor
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Model model,@UserParam UserInfo userInfo,Long tid){
        if(userInfo == null){
            AjaxResult ajaxResult = new AjaxResult(false, "登录先");
            ajaxResult.setCode(102);
            return ajaxResult;
        }
        //true则收藏,否则取消收藏
        boolean result = travelStatisRedisService.isTravelFavor(tid,userInfo.getId());

        return new AjaxResult(result,"").addData(travelStatisRedisService.getTravelStatisVO(tid));
    }




    /*  demo
        @RequestMapping("/info")
        @ResponseBody
        public Object info(@UserParam UserInfo user){
            return user;
        }
        @RequestMapping("/save")
        @ResponseBody
        public Object save(UserInfo user){
            return user;
        }
    */
}
